import re
from django_redis import get_redis_connection
from rest_framework import serializers
from users.models import User, Address
from rest_framework_jwt.settings import api_settings  # 自动导入会出错， 手动写


# 注册提交序列化器
class RegisterCreateSerializer(serializers.ModelSerializer):
    # 自定义模型类中没有的验证内容（短信验证码， 是否同意协议， 确认密码密码是否一致）
    password2 = serializers.CharField(label='校验密码', allow_null=False, allow_blank=False, write_only=True)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, allow_null=False, allow_blank=False,
                                     write_only=True)
    allow = serializers.CharField(label='是否同意协议', allow_null=False, allow_blank=False, write_only=True)

    token = serializers.CharField(label='登录状态token', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'mobile', 'password2', 'sms_code', 'allow', 'token']
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'max_length': 20,
                'min_length': 6,
                'error_messages': {
                    'max_length': '仅允许6-20位的用户名',
                    'min_length': '仅允许6-20位的用户名'
                }
            },
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 6,
                'error_messages': {
                    'max_length': '仅允许6-20位的密码',
                    'min_length': '仅允许6-20位的密码'
                }
            }
        }

    # 手机号码和同意协议是但字段验证
    # 手机号码验证
    def validate_mobile(self, mobile):
        if not re.match(r'1[3-9]\d{9}', mobile):
            raise serializers.ValidationError('手机号码不符合规范')
        return mobile

    # 验证是否同意协议
    def validate_allow(self, allow):
        if allow != 'true':
            raise serializers.ValidationError('请阅读并同意用户协议')
        return allow

    # 两次密码是否一致/短信验证码验证是多字段验证
    def validate(self, attrs):
        password = attrs['password']
        password2 = attrs['password2']
        if password != password2:
            raise serializers.ValidationError('两次密码不一致')
        # 获取用户提交来的短信验证码
        submited_sms_code = attrs['sms_code']
        # 从redis获取验证吗
        mobile = attrs['mobile']
        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_code_%s' % mobile)
        if not redis_sms_code:
            raise serializers.ValidationError('短信验证码过期')
        if redis_sms_code.decode() != submited_sms_code:
            raise serializers.ValidationError('短息验证码错误')
        return attrs

    # 删除不用入库的字段（短信验证码， 是否同意协议， 确认密码）
    def create(self, validated_data):

        # 删除多余字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)
        # 密码加密（内置set_password）
        user.set_password(validated_data['password'])
        user.save()

        # 生成记录登录状态的token
        # 获取两个方法, 用于处理数据和加密信息
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 用两个方法来处理加密用户信息
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user


# 邮箱激活
class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


# 在用户中心添加邮箱验证
class EmailSerializer(serializers.ModelSerializer):
    """
    邮箱序列化器
    """

    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        email = validated_data.get('email')
        instance.email = email
        instance.save()

        # 保存成功就发邮件
        from django.core.mail import send_mail
        from mall import settings
        from .models import User

        # 激活链接， 点击和复制到浏览器两种方式
        url = instance.generate_link_for_active_email()

        # subject = '美多商城邮箱验证'
        # massege = ''  # 普通邮件正文文本
        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (email, url, url)
        #
        # send_mail(subject, "", settings.EMAIL_FROM, [email], html_message=html_message)
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email, url)
        return instance


# 添加用户收货地址序列化器
class AddressSerializer(serializers.ModelSerializer):

    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


    def create(self, validated_data):
        #Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


# 修改收货地址标题序列化器
class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


from goods.models import SKU
from django_redis import get_redis_connection
# 用户历史记录 序列化  用户每访问一次商品详情页面就把该商品加入到历史记录的最前面
class AddUserBrowsingHistorySerializer(serializers.Serializer):
    """
    添加用户浏览记录序列化器
    """
    sku_id = serializers.IntegerField(label='商品编号',min_value=1,required=True)

    def validate_sku_id(self,value):
        """
        检查商品是否存在
        """
        try:
            SKU.objects.get(pk=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

    def create(self, validated_data):

        #获取用户信息， GenericAPIView会添加 request添加到context里并传序列化器
        user_id = self.context['request'].user.id
        #获取商品id
        sku_id = validated_data['sku_id']
        #连接redis
        redis_conn = get_redis_connection('history')
        #移除已经存在的本记录， 级不能有重复的记录
        redis_conn.lrem('history_%s'%user_id,0,sku_id)
        #添加新的记录， 新纪录要保持在最前面
        redis_conn.lpush('history_%s'%user_id,sku_id)
        #保存最多5条记录
        redis_conn.ltrim('history_%s'%user_id,0,4)
        return validated_data

# 获取历史记录序列化器
class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')